<template>
  <view class="container">
    <view class="loading" v-if="!currentDiscussionDetail.title">
      <van-loading type="spinner" vertical>加载中...</van-loading>
    </view>

    <view class="discussion" v-else>
      <!-- 标题 -->
      <view class="headerTitle"> {{ currentDiscussionDetail.title }} </view>

      <!-- 作者信息 -->
      <view class="author">
        <view class="leftInfo">
          <image
            :src="currentDiscussionDetail.author.avatar"
            class="avatar"
          ></image>
          <view class="authorDetail">
            <view class="name">{{
              currentDiscussionDetail.author.nickName
            }}</view>
            <view class="time">{{
              $formatTime.formatTimeToHHMM(currentDiscussionDetail.createTime)
            }}</view>
          </view>
        </view>
        <view v-if="showFocus" class="rightInfo">
          <van-button
            block
            size="small"
            :color="focusFlag ? '#CC0303' : '#05A47D'"
            @click="handleFocus"
          >
            {{ focusFlag ? "已关注" : "+ 关注" }}</van-button
          >
        </view>
      </view>

      <!-- 正文内容 -->
      <view class="discussionContent">
        <view class="text">
          {{ currentDiscussionDetail.content }}
        </view>
        <view class="images" v-if="currentDiscussionDetail.picList.length">
          <image
            :src="item"
            v-for="(item, index) in currentDiscussionDetail.picList"
            :key="index"
            class="image"
          ></image>
        </view>
      </view>

      <!-- 评论区 -->
      <view class="comment">
        <view class="commentTitle">
          <view class="commentInfo">
            <view class="commentHead">评论</view>
            <view class="commentCount">{{
              currentDiscussionDetail.commentCount
            }}</view>
          </view>
          <view class="sort" @click="showAction = true">
            <image src="../../static/icons/transform.png" class="icon" />
            <text>{{ [sortText[sortIndex]] }}</text>
          </view>
        </view>
        <view class="commentList">
          <CommentList :commentList="currentDiscussionDetail.commentList" />
        </view>
      </view>

      <!-- 排序弹出层 -->
      <van-action-sheet
        :show="showAction"
        :actions="sortRules"
        @select="chooseRules"
      />

      <!-- 发表评论 -->
      <view class="publishComment">
        <input
          type="text"
          placeholder="评论"
          placeholder-style="margin-left:15rpx"
          class="commentBox"
          v-model="commentContent"
          @confirm="sumbitComment"
        />
        <view class="operator">
          <view
            class="operatorDetail"
            v-for="(item, index) in commentIcon"
            :key="index"
            @click="handleOperator(index)"
          >
            <image
              :src="item.flag ? item.active : item.icon"
              class="commentIcon"
            ></image>
            <view :style="{ color: item.flag ? '#05A47D' : '#000' }">{{
              item.name
            }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import CommentList from "./components/CommentList.vue";
import { UserMessage } from "../../utils/messageController.js";
import { mapState } from "vuex";
export default {
  components: {
    CommentList,
  },
  data() {
    return {
      sortText: ["热门", "正序", "倒序"],
      sortIndex: 0,
      showAction: false,
      focusFlag: false,
      showFocus: false,
      commentContent: "",
      sortRules: [
        {
          id: 0,
          name: "热门",
        },
        {
          id: 1,
          name: "正序",
        },
        {
          id: 2,
          name: "倒序",
        },
      ],
      commentIcon: [
        {
          flag: false,
          icon: "../../static/icons/collection.png",
          active: "../../static/icons/collectionActive.png",
          name: "收藏",
        },
        {
          flag: false,
          icon: "../../static/icons/thumbs.png",
          active: "../../static/icons/thumbsActive.png",
          name: "点赞",
        },
        {
          flag: false,
          icon: "../../static/icons/comment2.png",
          active: "../../static/icons/comment2Active.png",
          name: "评论",
        },
      ],
    };
  },
  computed: { ...mapState("m_discussion", ["currentDiscussionDetail"]) },

  onLoad(options) {
    const id = options.id;
    this.$store.dispatch("m_discussion/getCurrentDicussionDetail", id);
  },

  watch: {
    currentDiscussionDetail(newValue) {
      console.log("check:", this.currentDiscussionDetail.commentList);
      this.initOperatorStatus(newValue._id);
      const userInfo = this.$store.state.userInfo;
      if (newValue._openid !== userInfo._openid) {
        this.showFocus = true;
      }
    },
  },

  methods: {
    // 关注/取关逻辑
    async handleFocus() {
      const isFocus = !this.focusFlag,
        focusId = this.currentDiscussionDetail._openid;
      try {
        this.focusFlag ? this.handleSendMessage(0) : this.handleSendMessage(1);
        await this.$store.dispatch("focusUser", { focusId, isFocus });
        if (isFocus) {
          uni.showToast({
            icon: "success",
            title: "关注成功",
          });
        } else {
          uni.showToast({
            icon: "success",
            title: "取关成功",
          });
        }
      } catch (err) {
        console.log("关注逻辑出错：", err);
      }

      this.focusFlag = !this.focusFlag;
    },

    // 发表评论
    async sumbitComment() {
      if (!this.judgeIsLogin()) {
        return;
      }
      if (!this.commentContent.trim().length) {
        uni.showToast({
          icon: "error",
          title: "请先输入内容",
          duration: 1000,
        });
        return;
      }
      if (this.commentContent.trim().length >= 80) {
        uni.showToast({
          icon: "error",
          title: "评论过长",
          duration: 1000,
        });
        return;
      }
      const comment = {},
        discussionId = this.currentDiscussionDetail._id,
        userInfo = this.$store.state.userInfo;
      comment.content = this.commentContent.trim();
      comment.time = new Date();
      comment.liked = 0;
      comment.id = this.currentDiscussionDetail.commentList.length + 1;
      comment.author = {};
      comment.author.nickName = userInfo.nickName;
      comment.author.avatar = userInfo.avatar;
      comment.author._openid = userInfo._openid;
      console.log("checkAuthor:", comment.author);
      try {
        await this.$store.dispatch("addDiscussionComment", {
          comment,
          discussionId,
        });
        this.getDiscussionList(); // 刷新讨论列表
        uni.showToast({
          icon: "success",
          title: "发表评论成功",
          duration: 1000,
        });
        this.commentContent = "";
        return;
      } catch (err) {
        console.log(err);
      }
    },

    // 排序规则逻辑
    chooseRules(item) {
      this.showAction = false;
      this.sortIndex = item.detail.id;
      console.log("排序规则：", this.sortIndex);
      this.$store.commit("m_discussion/sortComment", this.sortIndex);
    },

    // 发表评论图标逻辑
    async handleOperator(index) {
      if (!this.judgeIsLogin()) {
        return;
      }
      if (index === 0) {
        this.handleCollectionDiscussion(index);
        return;
      }
      if (index === 1) {
        this.handleLikeDiscussion(index);
        return;
      }
      this.getDiscussionList(); // 刷新讨论列表
    },

    // 点赞逻辑处理
    async handleLikeDiscussion(index) {
      if (this.commentIcon[index].flag) {
        uni.showToast({
          icon: "error",
          title: "已点过赞",
          duration: 1000,
        });
        return;
      }
      try {
        const discussionId = this.currentDiscussionDetail._id,
          authorId = this.currentDiscussionDetail._openid;
        await this.$store.dispatch("m_discussion/likeDicussion", {
          discussionId,
          authorId,
        });
        uni.showToast({
          icon: "success",
          title: "点赞成功",
          duration: 1000,
        });
        this.commentIcon[index].flag = true;
      } catch (err) {
        console.log(err);
      }
    },

    // 收藏逻辑处理
    async handleCollectionDiscussion(index) {
      const discussionId = this.currentDiscussionDetail._id;
      let isCollection = true;
      if (this.commentIcon[index].flag) {
        isCollection = false;
        await this.$store.dispatch("handleCollectionDiscussion", {
          discussionId,
          isCollection,
        });
        uni.showToast({
          icon: "success",
          title: "已取消收藏",
          duration: 1000,
        });
        this.commentIcon[index].flag = false;
        return;
      }
      try {
        await this.$store.dispatch("handleCollectionDiscussion", {
          discussionId,
          isCollection,
        });
        uni.showToast({
          icon: "success",
          title: "收藏成功",
          duration: 1000,
        });
        this.commentIcon[index].flag = true;
      } catch (err) {
        console.log(err);
      }
    },

    // 初始化操作部分状态
    initOperatorStatus(id) {
      const userInfo = this.$store.state.userInfo;
      if (userInfo.collection.includes(id)) {
        this.commentIcon[0].flag = true;
      }
      if (userInfo.focusList.includes(this.currentDiscussionDetail._openid)) {
        this.focusFlag = true;
      }
    },

    // 评论点赞收藏等刷新讨论列表
    async getDiscussionList(page = 0, limitCount = 10) {
      await this.$store.dispatch("m_discussion/getDiscussionList", {
        page,
        limitCount,
      });
    },

    // 判断用户是否登录
    judgeIsLogin() {
      const userInfo = this.$store.state.userInfo;
      if (!userInfo.avatar.length || !userInfo.nickName.length) {
        uni.showToast({
          icon: "error",
          title: "请先进行登录",
          duration: 1000,
        });
        return false;
      }
      return true;
    },

    // 发布关注/取消关注的消息
    async handleSendMessage(isFocus) {
      const receiveId = this.currentDiscussionDetail._openid,
        focusName = this.$store.state.userInfo.nickName,
        messageItem =
          isFocus === 1
            ? new UserMessage().messageForFocus({ receiveId, focusName })
            : new UserMessage().messageForCancelFocus({ receiveId, focusName });
      console.log("check:", messageItem);
      await this.$store.dispatch("m_message/sendMessage", messageItem);
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.discussion {
  width: 95%;
  padding: 20rpx 20rpx 100rpx 20rpx;
  background-color: #fff;
  .headerTitle {
    font-weight: 700;
    font-size: 45rpx;
  }

  .author {
    padding: 15rpx 5rpx;
    position: sticky;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20rpx 0;
    .leftInfo {
      display: flex;
      .avatar {
        width: 85rpx;
        height: 85rpx;
        border-radius: 50%;
      }
      .authorDetail {
        margin-left: 10rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .name {
          font-weight: 500;
        }
        .time {
          font-size: 24rpx;
          color: #aaa;
        }
      }
    }
  }

  .discussionContent {
    display: flex;
    flex-direction: column;
    width: 100%;
    .images {
      margin-top: 20rpx;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      .image {
        margin-bottom: 26rpx;
        width: 100%;
        height: 400rpx;
        border-radius: 10rpx;
      }
    }
    .operator {
      display: flex;
      align-items: center;
      view {
        padding: 10rpx 15rpx;
        margin-right: 10rpx;
        image {
          width: 50rpx;
          height: 50rpx;
          margin-right: 10rpx;
        }
      }
    }
  }

  .comment {
    display: flex;
    flex-direction: column;
    margin-top: 30rpx;
    .commentTitle {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10rpx;
      border-bottom: 1rpx solid #eee;
      .commentInfo {
        display: flex;
        .commentHead {
          position: relative;
          margin-right: 10rpx;
          &::after {
            position: absolute;
            content: "";
            display: inline-block;
            bottom: -10rpx;
            left: 5rpx;
            width: 60rpx;
            height: 4rpx;
            background-color: #05a47d;
          }
        }
      }
      .sort {
        color: #aaa;
        display: flex;
        align-items: center;
        font-size: 26rpx;
        .icon {
          width: 30rpx;
          height: 30rpx;
          margin-right: 10rpx;
        }
      }
    }
  }

  .publishComment {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100vw;
    height: 100rpx;
    box-sizing: border-box;
    background-color: #fff;
    padding: 10rpx 20rpx;
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    .commentBox {
      width: 55%;
      height: 100%;
      background-color: #eff;
      border-radius: 10rpx;
    }

    .operator {
      flex: 1;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .operatorDetail {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 24rpx;
      }
      .commentIcon {
        width: 45rpx;
        height: 45rpx;
      }
    }
  }
}
</style>

<style>
page {
  background-color: #fff;
  height: 100%;
}
</style>
